<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>二手市场</title>
    <!-- 引入若依默认样式和脚本 -->
    <th:block th:include="include :: header('二手交易系统')"/>
    <style>
        .product-card {
            transition: all 0.3s;
            margin-bottom: 20px;
        }

        .product-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, .1);
        }

        .product-img {
            width: 100%; /* 确保图片宽度适应容器 */
            max-width: 100%; /* 确保图片不会超出容器 */
            height: 127px !important; /* 固定高度 */
            object-fit: contain; /* 保持图片的宽高比，并确保图片完全显示在容器内 */
            margin: 0 5px; /* 两侧保留 5px 的间距 */
        }

        .price-tag {
            color: #ff5000;
            font-size: 1.5rem;
            font-weight: bold;
        }

        .search-box {
            background: #f5f5f5;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 30px;
        }


        /* 支付方式样式 */
        .payment-methods {
            margin-top: 15px;
        }

        .payment-option {
            border: 2px solid #ddd;
            border-radius: 8px;
            padding: 10px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            background: #f8f9fa;
        }

        .payment-option:hover {
            border-color: #007bff;
        }

        .payment-option.active {
            border-color: #28a745;
            background-color: #e9f5e9;
        }

        .payment-img {
            width: 80px;
            height: 80px;
            object-fit: contain;
            margin-bottom: 8px;
        }

        .payment-name {
            color: #666;
            font-size: 14px;
            font-weight: 500;
        }
    </style>
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
    <!-- 头部导航 -->
    <!-- 使用 th:replace 并指定完整路径 -->
    <!--    <div th:replace="~{include/topnav :: top-nav}"></div>-->

    <div class="content-wrapper">
        <section class="content-header">
            <h1>理梦二手物品交易</h1>
        </section>

        <section class="content">
            <!-- 搜索筛选区域 -->
            <div class="search-box">
                <form id="searchForm">
                    <div class="row">
                        <div class="col-md-3">
                            <input class="form-control" name="productName" id="productName" placeholder="商品名称" type="text">
                        </div>
                        <div class="col-md-3">
                            <select class="form-control" name="categoryId" id="categoryId">
                                <option value="">所有分类</option>
                                <!-- 动态加载分类 -->
                                <option th:each="c : ${categories}"
                                        th:text="${c.name}"
                                        th:value="${c.id}"></option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <button class="btn btn-primary btn-block" onclick="loadProducts()" type="button">
                                <i class="fa fa-search"></i> 搜索
                            </button>
                        </div>
                    </div>
                </form>
            </div>

            <!-- 商品展示区域 -->
            <div class="row" id="productList"></div>

            <!-- 购物车面板 - 固定定位在底部 -->
            <div class="col-sm-12" style="padding: 15px;">
                <div class="panel panel-info">
                    <div class="panel-heading">购物车</div>
                    <div class="panel-body">
                        <p id="cart-items">当前购物车为空</p>
                        <p id="total-value">总价值：0 元</p>
                        <!-- 加入结算按钮 -->
                        <button class="btn btn-primary" id="settlementButton">结算</button>
                    </div>
                </div>
            </div>

            <!-- 分页控件 -->
            <div class="row">
                <div class="col-md-12">
                    <div class="text-center" id="pagination"></div>
                </div>
            </div>
        </section>
    </div>
</div>

<!-- 商品卡片模板（隐藏） -->
<script id="productTemplate" type="text/template">
    <div class="col-md-3">
        <div class="product-card">
            <div class="thumbnail">
                <img src="{{imgUrl}}" class="product-img" alt="{{name}}">
                <div class="caption">
                    <h4>{{productName}}</h4>
                    <p class="text-muted">{{category}}</p>
                    <div class="price-tag">¥{{productPrice}}</div>
                    <p>卖家：{{owner}}</p>
                    <p style="color: #888; font-size: 12px;">库存：{{productStock}}</p>
                    <button class="btn btn-success btn-block"
                            onclick="addToCart({{id}}, '{{productName}}', {{productPrice}}, 0, {{productStock}})">
                        <i class="fa fa-cart-plus"></i> 添加购物车
                    </button>
                    <button class="btn btn-danger btn-block remove-from-cart" data-id="{{id}}" data-pro-type="0" onclick="removeFromCart({{id}}, 0)"
                            style="display: none;">
                        <i class="fa fa-minus"></i> 移除购物车
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 地址输入模态框 -->
    <!-- 地址输入模态框 -->
    <div class="modal fade" id="addressModal" tabindex="-1" role="dialog" aria-labelledby="addressModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h4 class="modal-title" id="addressModalLabel">请输入收货地址并选择支付方式</h4>
                </div>
                <div class="modal-body">
                    <form id="addressForm">
                        <div class="form-group">
                            <label for="address">详细地址</label>
                            <textarea class="form-control" id="address" rows="3" required></textarea>
                        </div>
                        <div class="form-group">
                            <label>选择支付方式</label>
                            <div class="payment-methods row">
                                <div class="col-xs-6">
                                    <div class="payment-option active" data-method="alipay">
                                        <img th:src="@{/img/zfb.png}"
                                             src="src/main/resources/static/img/zfb.png"
                                             class="payment-img"
                                             alt="支付宝">
                                        <div class="payment-name">支付宝</div>
                                        <input type="radio" name="paymentMethod"
                                               value="alipay" checked hidden>
                                    </div>
                                </div>
                                <div class="col-xs-6">
                                    <div class="payment-option" data-method="wxpay">
                                        <img th:src="@{/img/wx.png}"
                                             src="src/main/resources/static/img/wx.png"
                                             class="payment-img"
                                             alt="微信支付">
                                        <div class="payment-name">微信支付</div>
                                        <input type="radio" name="paymentMethod"
                                               value="wxpay" hidden>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="confirmAddress" onclick="confirmAddress()">确认</button>
                </div>
            </div>
        </div>
    </div>
</script>

<th:block th:include="include :: footer"/>
<script>

    var createOrderUrl = ctx + "system/shopping/create";
    var cartMap = {};

    function updateCartItems(cartData) {
        console.log("cartData:{}", JSON.stringify(cartData))
        console.log("cartMap:{}", JSON.stringify(cartMap))
        var itemsText = '';
        var totalValue = 0;
        for (var item of cartData) {
            if (item.type === 'add') {
                if (cartMap[item.id + '_' + item.proType]) {
                    console.log("add...")
                    cartMap[item.id + '_' + item.proType].quantity++;
                } else {
                    cartMap[item.id + '_' + item.proType] = {
                        name: item.name,
                        price: item.price,
                        quantity: 1,
                        proType: item.proType
                    };
                }
            } else if (item.type === 'remove') {
                console.log("remove...")
                if (cartMap[item.id + '_' + item.proType] && cartMap[item.id + '_' + item.proType].quantity > 0) {
                    cartMap[item.id + '_' + item.proType].quantity--;
                    if (cartMap[item.id + '_' + item.proType].quantity === 0) {
                        delete cartMap[item.id + '_' + item.proType];
                    }
                }
            }
        }

        for (var itemName in cartMap) {
            console.log("itemName :", itemName);
            var item = cartMap[itemName];
            itemsText += item.name + '*' + item.quantity + ', ';
            totalValue += item.price * item.quantity;
        }

        itemsText = itemsText.slice(0, -2); // 去除最后多余的逗号和空格

        $('#cart-items').text(itemsText);
        $('#total-value').text('总价值：' + totalValue + ' 元');

        checkCartEmpty();
        updateRemoveButtons();
    }

    function createOrder(address) {
        var cartData = [];
        for (var itemName in cartMap) {
            var item = cartMap[itemName];
            cartData.push({
                id: itemName,
                proType: item.proType,
                quantity: item.quantity
            });
        }

        $.ajax({
            type: 'POST',
            url: createOrderUrl,
            dataType: 'json',
            data: JSON.stringify({
                shoppingDTOList: cartData,
                address: address
            }),
            contentType: "application/json; charset=utf-8",
            success: function (response) {
                console.log(JSON.stringify({
                    shoppingDTOList: cartData,
                    address: address
                }));
                // 弹窗提示
                alert('订单创建成功');
                // 清空购物车
                cartMap = {};
                updateCartItems([]);
            },
            error: function (error) {
                console.log(error);
                alert('订单创建失败');
            }
        });
    }

    // 为结算按钮添加点击事件
    $('#settlementButton').click(function () {
        if (Object.keys(cartMap).length === 0) {
            alert('购物车为空，请先添加商品');
            return;
        }
        $('#addressModal').modal('show');
    });

    // 确认地址按钮点击事件
    // $('#confirmAddress').click(function () {
    //     console.log("confirmAddress...")
    //     var address = $('#address').val().trim();
    //     if (!address) {
    //         alert('请输入收货地址');
    //         return;
    //     }
    //     $('#addressModal').modal('hide');
    //     createOrder(address);
    // });

    function confirmAddress() {
        console.log("confirmAddress...")
        var address = $('#address').val().trim();
        if (!address) {
            alert('请输入收货地址');
            return;
        }

        var paymentMethod = $('input[name="paymentMethod"]:checked').val();
        if (!paymentMethod) {
            alert('请选择支付方式');
            return;
        }
        $('#addressModal').modal('hide');
        createOrder(address);
    }
    // 添加到购物车的操作函数
    function addToCart(id, name, price, proType, quantity) {
        if (cartMap[id + '_' + proType] && cartMap[id + '_' + proType].quantity >= quantity) {
            alert('该商品已达到最大购买数量');
            return;
        }
        updateCartItems([{id: id, name: name, price: price, type: "add", proType: proType}]);
    };

    // 移除的操作函数
    function removeFromCart(id, proType) {
        console.log("移除购物车 :", id);
        updateCartItems([{id: id, type: "remove", proType: proType}]);
    };

    // 检查购物车是否为空，并相应地设置结算按钮的状态
    function checkCartEmpty() {
        if (Object.keys(cartMap).length === 0) {
            $('#settlementButton').prop('disabled', true);
        } else {
            $('#settlementButton').prop('disabled', false);
        }
    }

    // 更新移除按钮的显示状态
    function updateRemoveButtons() {
        // 隐藏所有移除按钮
        $('.remove-from-cart').hide();

        // 遍历 cartMap，显示对应的移除按钮
        for (var key in cartMap) {
            if (cartMap.hasOwnProperty(key)) {
                var parts = key.split('_');
                var id = parts[0];
                var proType = parts[1];

                var button = $('.remove-from-cart[data-id="' + id + '"][data-pro-type="' + proType + '"]');
                if (button.length > 0) {
                    button.show();
                }
            }
        }
    }


    // 监听购物车变化
    $(document).on('click', '.btn-success', function () {
        if (Object.keys(cartMap).length > 0) {
            $('#settlementButton').prop('disabled', false);
        }
    });

    $(document).on('click', '.btn-danger', function () {
        if (Object.keys(cartMap).length === 0) {
            $('#settlementButton').prop('disabled', true);
        }
    });
    // 页面初始化加载商品
    $(function () {
        console.log("页面初始化加载商品...");
        loadProducts(1);
        // 初始化时检查购物车状态
        checkCartEmpty();
    });

    // 加载商品列表
    function loadProducts(pageNum) {
        var categoryId = $('#categoryId').val();
        var productName = $('#productName').val();
        console.log("loadProducts...", categoryId, productName);
        $.ajax({
            url: ctx + "system/product/listV2",
            dataType: "json",
            type: "POST",
            data: {
                pageNum: pageNum,
                pageSize: 100,
                categoryId: categoryId,
                productName: productName
            },
            success: function (res) {
                renderProducts(res.rows);
                renderPagination(res.total, pageNum);
            }
        });
    }

    // 渲染商品卡片
    function renderProducts(products) {
        console.log("渲染商品卡片:", products);
        const template = $("#productTemplate").html();
        const html = products.map(p => {
            return template.replace(/{{(.*?)}}/g, (m, p1) => p[p1]);
        }).join('');
        $("#productList").html(html);
    }

    // 渲染分页
    function renderPagination(total, current) {
        $("#pagination").pagination({
            total: total,
            pageSize: 8,
            current: current,
            callback: function (page) {
                loadProducts(page);
            }
        });
    }

    // 查看详情（需补充实现）
    function viewDetail(id) {
        // window.location.href = ctx + "system/product/detail/" + id;
        alert("商品详情功能待实现 - ID:" + id);
    }
</script>
</body>
</html>